<template>
  <div>
    <div class="app-container">
      <!-- :right="{ to: '/app/setting', icon: 'el-icon-setting' }" -->

      <Header
        class="app-container"
        :title="
          `${channel.name} ${
            channel.is_typing ? '正在输入' : '...............'
          }`
        "
      />

      <mt-loadmore ref="loadmore" :top-method="loadTop">
        <div ref="main" class="main">
          <div ref="content">
            <!-- {{ messages }} -->
            <div>
              <div v-for="msg in messages" :key="msg.id">
                <div>{{ msg.id }}, {{ msg.date }}</div>
                <div align="center">{{ format_date(msg) }}</div>
                <el-row :gutter="20">
                  <el-col v-if="align(msg) === 'left'" :span="4">
                    <div align="left">
                      <img :src="get_image(msg)" width="40" height="40" />
                    </div>
                  </el-col>
                  <el-col :span="20">
                    <div :align="align(msg)">
                      <div v-if="msg.model === 'mail.channel'">
                        <ChatText :message="msg" />
                      </div>
                      <div v-else>
                        <ChatOrder :message="msg" />
                      </div>
                    </div>
                  </el-col>
                  <el-col v-if="align(msg) === 'right'" :span="4">
                    <div align="right)">
                      <img :src="get_image(msg)" width="40" height="40" />
                    </div>
                  </el-col>
                </el-row>

                <el-divider />
              </div>
              <div>&nbsp;</div>
              <div>&nbsp;</div>
            </div>
          </div>
        </div>
      </mt-loadmore>

      <div>
        <!-- {{ channel }}
        <div v-for="ptn in channel.channel_partner_ids__objects" :key="ptn.id">
          {{ ptn.id }},{{ ptn.name }},{{ ptn.is_typing }},{{
            ptn.last_message_id
          }}
        </div> -->
      </div>

      <mt-tabbar fixed>
        <el-row :gutter="20">
          <el-col :span="18">
            <!-- type="textarea" -->
            <mt-field
              v-model="chat"
              label=""
              placeholder="输入新消息"
              rows="2"
              @keyup.enter.native="handleChat"
              @blur.native.capture="handleBlur"
              @focus.native.capture="handleFocus"
            />
          </el-col>
          <el-col :span="3">
            <mt-button
              align="left"
              size="small"
              class="el-icon-check"
              @click.native="handleChat"
            />
          </el-col>
          <el-col :span="3">
            <mt-button
              align="right"
              size="small"
              class="el-icon-plus"
              @click.native="handlePlus"
            />
          </el-col>
        </el-row>
      </mt-tabbar>

      <mt-popup v-model="popupVisible" position="bottom">
        ...
      </mt-popup>
    </div>
  </div>
</template>

<script>
import { parseTime } from '@/utils'

import ChatText from './chatText'
import ChatOrder from './chatOrder'
import Header from '@/components3/Header'

// import odoo from '@/odooapi'

export default {
  name: 'Message',
  components: { Header, ChatText, ChatOrder },
  // directives: {},
  // filters: {},

  data() {
    return {
      chat: '',
      popupVisible: false,
      inputPath: '/app/consult/survey-input'
    }
  },
  computed: {
    //
    channel: function() {
      return this.$store.state.appChat.channel
    },
    messages: function() {
      return this.$store.state.appChat.messages
    },

    isScroll: function() {
      return this.$store.state.appChat.isScroll
    },

    isEmployee: function() {
      return this.$store.state.appMe.isEmployee
    },

    user_partner_id: function() {
      return this.$store.state.appMe.partner_id
    },

    consultation: function() {
      return this.$store.state.appConsultation.dataDict
    }
  },

  watch: {
    //
    messages: function() {
      if (this.isScroll) {
        this.scroll()
      }
    }
  },

  async created() {
    this.$store.dispatch('appMe/getInfo')
    const { id } = this.$route.query
    const channel_id = parseInt(id)
    await this.$store.dispatch('appChat/initChannel', channel_id)
  },

  mounted() {
    //
  },

  methods: {
    // 屏幕滚动
    scroll() {
      this.$nextTick(() => {
        this.$refs.main.scrollTop = this.$refs.content.scrollHeight
      })
    },

    // 下拉 加载历史消息
    async loadTop() {
      this.$store.dispatch('appChat/fetchHistory')

      // await this.fetchHistory()

      this.$refs.loadmore.onTopLoaded()
    },

    format_date(message) {
      const getNewDate = str => {
        return new Date(str.replace(/-/g, '/'))
      }

      const get_date_show = (date, date_last) => {
        //
        if (!date_last) {
          return date
        }

        // if (! getNewDate(date).getMinutes() % 10) {
        //   return date
        // }

        // console.log('xxxxx,message, ', message, date, date_last)

        if (getNewDate(date) - getNewDate(date_last) > 1000 * 60) {
          return date
        }

        return null
      }

      const index = this.messages.findIndex(item => item.id === message.id)
      const date_last = index ? this.messages[index - 1].date : null

      const date_show = get_date_show(message.date, date_last)

      if (!date_show) {
        return null
      }

      const dt2 = new Date(getNewDate(date_show).getTime() + 1000 * 60 * 60 * 8)

      const today = parseTime(new Date(), '{y}-{m}-{d}')
      const dt2_yyyymmdd = parseTime(dt2, '{y}-{m}-{d}')

      if (dt2_yyyymmdd === today) {
        return `今天 ${parseTime(dt2, '{h}:{i}')}`
      } else if (getNewDate(today) - getNewDate(dt2_yyyymmdd) === 86400000) {
        return `昨天 ${parseTime(dt2, '{h}:{i}')}`
      } else {
        return parseTime(dt2, '{y}-{m}-{d} {h}:{i}')
      }
    },

    get_image(msg) {
      const baseURL = process.env.VUE_APP_BASE_API
      const imgUrl = '/web/image'
      const image_url = `${baseURL}${imgUrl}?model=res.partner&id=${
        msg.author_id[0]
      }&field=image_1920`
      return image_url
    },

    align(row) {
      return row.author_id[0] === this.user_partner_id ? 'right' : 'left'
    },

    handleFocus() {
      // console.log('xxxx, handleFocus')
      // this.post_notify_typing(true)
      this.$store.dispatch('appChat/postNotifyTyping', true)
    },

    handleBlur() {
      // console.log('xxxx, handleBlur')
      this.$store.dispatch('appChat/postNotifyTyping', false)
      // this.post_notify_typing(false)
    },

    handleChat() {
      this.$store.dispatch('appChat/postMessage', this.chat)
      this.chat = ''
    },

    async handlePlus() {
      console.log('handlePlus')

      if (!this.isEmployee) {
        // 取得 当前的 咨询单
        await this.$store.dispatch(
          'appConsultation/consultation_get',
          this.channel.partner_id
        )

        // 发消息
        this.$store.dispatch('appConsultation/message_post', {
          id: this.consultation.id,
          body: '',
          author_id: this.channel.partner_id,
          channel_ids: [this.channel.id]
        })

        // const res2 = SO.call('message_post', [1], {
        //   //
        //   body: '',
        //   author_id: this.channel.partner_id,
        //   channel_ids: [this.channel.id]
        // })
      }

      //
      // if (this.whoAmI === 'customer') {
      //   const consultant_id = this.channel.partner_id
      //   const consultee_id = this.channel.me_partner_id
      //   console.log('handlePlus', this.whoAmI, consultant_id, consultee_id)
      //   this.post_consult_consultation({ consultant_id, consultee_id })
      //   // await this.find_regiter({ doctor_id, customer_id })
      // }
      // if (this.whoAmI === 'salesperson') {
      //   const consultee_id = this.channel.partner_id
      //   const consultant_id = this.channel.me_partner_id
      //   console.log('handlePlus', this.whoAmI, consultant_id, consultee_id)
      //   this.post_consult_survey({ consultant_id, consultee_id })
      //   // await this.find_regiter({ doctor_id, customer_id })
      // }
      // const SO = this.Model.env('sale.order')
      // const res = await SO.search({ fields: { name: null } })
      // const order_id = res[0].id
      // this.create_question_order()
      // const SO = this.Model.env('sale.order.template')
      // console.log('handlePlus 2', res2)
      // this.popupVisible = true
      // this.Model.private_message_post(this.channel.id, this.chat)
      // this.chat = ''
    }
  }
}
</script>

<style type="text/css">
.main {
  width: 100%;
  height: 600px;
  padding: 10px;
  box-sizing: border-box;
  background-color: pink;
  overflow: auto;
}
</style>
